package com.wzh.project.swing;

import java.awt.BorderLayout;
import java.awt.Container;

import javax.swing.JFrame;
import javax.swing.JTree;
import javax.swing.WindowConstants;
import javax.swing.event.TreeSelectionEvent;
import javax.swing.event.TreeSelectionListener;
import javax.swing.tree.DefaultMutableTreeNode;
import javax.swing.tree.DefaultTreeModel;
import javax.swing.tree.TreePath;
import javax.swing.tree.TreeSelectionModel;
 
public class TreeSelection extends JFrame {
	
	public TreeSelection(){
		Container c=getContentPane();
		setDefaultCloseOperation(WindowConstants.EXIT_ON_CLOSE);
	    setSize(200,300);
	    
	    
	    
	    
	    DefaultMutableTreeNode root = new DefaultMutableTreeNode("根节点");
	    DefaultMutableTreeNode child1 = new DefaultMutableTreeNode("子节点A");
	    DefaultMutableTreeNode child2 = new DefaultMutableTreeNode("子节点B");
	    
	    DefaultMutableTreeNode childchild1 = new DefaultMutableTreeNode("子节点AA",false);
	    DefaultMutableTreeNode childchild2 = new DefaultMutableTreeNode("子节点BB",false);
	    
	    root.add(child1);
	    root.add(child2);
	    child1.add(childchild1);
	    child2.add(childchild2);
	    DefaultTreeModel dt=new DefaultTreeModel(root,true);
	    final JTree jt = new JTree(dt);
	    
	    c.add(jt,BorderLayout.WEST);
	    setVisible(true);
	    
	    TreeSelectionModel treeselect = jt.getSelectionModel();
	    treeselect.setSelectionMode(TreeSelectionModel.CONTIGUOUS_TREE_SELECTION);
	    
	    jt.addTreeSelectionListener(new TreeSelectionListener() {
			
			@Override
			public void valueChanged(TreeSelectionEvent e) {
				// TODO Auto-generated method stub
				if(!jt.isSelectionEmpty()){
					TreePath[] selectionpath=jt.getSelectionPaths();  //获得所有被选中的节点
					for(int i=0;i<selectionpath.length;i++){
						TreePath treepath=selectionpath[i];  
						//object 数组的形式返回数组
						Object[] path=treepath.getPath();
						for(int j=0;j<path.length;j++){
							DefaultMutableTreeNode node=(DefaultMutableTreeNode)path[i];
							String s=node.getUserObject()+(j==(path.length-1)?"":"-->");
							System.out.println(s);
							
						}
						System.out.println();
						
					}
				}
			}
		});
	}
	public static void main(String[] args) {
		// TODO Auto-generated method stub
		new TreeSelection();
	}
}
